package chris.deadLetter;

import chris.ConFactory;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * DLSend
 *
 * @author nanxin.chen
 * @since 2017/8/2
 */
public class DLSend {
    public static final String queueName    = "normal-queue";
    public static final String exchangeName = "normal-exchange";

    public static final String DLQueueName    = "dead-letter-queue";
    public static final String DLExchangeName = "dead-letter-exchange";
    public static final String DLRoutingKey   = "dl-routing-key";


    public static void main(String[] args) throws IOException, TimeoutException {
        Connection con = ConFactory.getConnectionFactory().newConnection();
        Channel channel = con.createChannel();

        //死信交换机  和  死信队列 声明
        channel.exchangeDeclare(DLExchangeName, BuiltinExchangeType.DIRECT);
        channel.queueDeclare(DLQueueName, true, false, false, null);
        channel.queueBind(DLQueueName, DLExchangeName, DLRoutingKey);


        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT);
        //设置普通队列 的死信转发规则, 及通过那个死信交换机转发, 转发的routing-key
        Map<String, Object> params = new HashMap<>();
        params.put("x-dead-letter-exchange", DLExchangeName);
        params.put("x-dead-letter-routing-key", DLRoutingKey); //可选
        channel.queueDeclare(queueName, false, false, false, params);
        channel.queueBind(queueName, exchangeName, "");

        //推送信息
        channel.basicPublish(exchangeName, "", null, "dead message".getBytes("utf-8"));

        channel.close();
        con.close();
    }
}
